package com.crm.system.controller.customerManager;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.model.entity.customerManager.*;
import com.crm.model.qo.customerManager.CustomerPoolAddQO;
import com.crm.model.qo.customerManager.CustomerPoolQO;
import com.crm.model.vo.cluePoolManager.UserCompanyVO;
import com.crm.model.vo.customerManager.*;
import com.crm.system.service.customerManager.CustomerPoolCompanyService;
import com.crm.system.service.customerManager.CustomerPoolRuleService;
import com.crm.system.service.customerManager.CustomerPoolService;
import com.crm.system.service.customerManager.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户公海
 * @ Author ：pym
 * @ Date   ：2021/1/15 10:09
 */
@RestController
@RequestMapping("/customer")
@Slf4j
public class CustomerPoolController {

    @Value("${esurl}")
    public String ESurl;

    @Autowired
    CustomerPoolService customerPoolService;

    @Autowired
    CustomerPoolCompanyService customerPoolCompanyService;

    @Autowired
    CustomerPoolRuleService customerPoolRuleService;

    @Autowired
    CustomerService customerService;

    /**
     * 管理模块 -- 客户公海列表
     * @return
     */
    @PostMapping("/customerPoolList")
    public DataResponse customerPoolList(HttpServletRequest request,
                                             @RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                             @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                             @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                             @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                             CustomerPoolQO customerPoolQO//查询条件
    ){
        try{
            DhPageInfo<CustomerPoolVO> customerPoolVOList = customerPoolService.selectCustomerPoolVOList(pageIndex,pageSize,customerPoolQO,sortName,sortOrder);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerPoolVOList);
        }catch(Exception e){
            log.error("customer customerPoolList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 新增客户池
     * @param customerPoolAddQO
     * @return
     */
    @PostMapping("/addCustomerPool")
    public DataResponse addCustomerPool(HttpServletRequest request,
                                          @RequestBody CustomerPoolAddQO customerPoolAddQO) {
        try {
            Boolean result = customerPoolService.addCustomerPool(customerPoolAddQO);
            if (result) {
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            } else {
                return new DhResponse(ResponseCodeEnum.CUSTOMER_POOL_NAME_EXIST.getResponseCode());
            }
        }catch(Exception e){
            log.error("customer addCustomerPool error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }

    }

    /**
     *线索池表单--开启/停用线索池(备注:只有全国池线索池才有)
     * @return
     */
    @PostMapping("/updatePoolState")
    public DataResponse updatePoolState(@RequestParam(value="customerPoolId",required = false) String customerPoolId,
                                        @RequestParam(value="poolState",required = false) String poolState
    ){
        try{
            Boolean result =  customerPoolService.updatePoolStateById(customerPoolId,poolState);
            if(result){
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }catch(Exception e){
            log.error("customer updatePoolState error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 根据客户id查询客户详细信息
     * @param customer_id 客户id
     * @return
     */
    @PostMapping("/customerHighSeasDetail")
    public DataResponse getCluePoolRule(@RequestParam(value="customer_id") String customer_id){
        try{
            Customer Customer = customerPoolService.customerHighSeasDetail(customer_id);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),Customer);
        }catch(Exception e){
            log.error("customer customerHighSeasDetail error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 根据客户id查询公司信息
     * @param customer_id 客户id
     * @return
     */
    @PostMapping("/companyInfo")
    public DataResponse getCompanyInfo(@RequestParam(value="customer_id",required = false) String customer_id){
        try{
            CustomerCompanyInfo customerCompanyInfo = customerPoolService.getCompanyInfo(customer_id);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerCompanyInfo);
        }catch(Exception e){
            log.error("customer companyInfo error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 根据客户id查询公司联系人信息
     * @param pageIndex 页码
     * @param pageSize 分页大小
     * @param sortName 排序列名字
     * @param sortOrder 排序规则(asc/desc)
     * @param customer_id 客户id
     * @param isSeniorExecutive   类型是否高管   0高管  1非高管
     * @param abolishState 废止状态  1不查询废止的 2查询废止的
     * @return
     */
    @PostMapping("/customerContactPersonList")
    public DataResponse customerContactPersonList(
            @RequestParam(value = "pageIndex", required = true) Integer pageIndex,
            @RequestParam(value = "pageSize", required = true) Integer pageSize,
            @RequestParam(value="sortName",required = false) String sortName,
            @RequestParam(value="sortOrder",required = false) String sortOrder,//排序(asc/desc)
            @RequestParam(value="customer_id",required = true) String customer_id,
            @RequestParam(value="isSeniorExecutive",required = false) int isSeniorExecutive,
            @RequestParam(value="abolishState",required = false) int abolishState){
        try{
            DhPageInfo<CustomerContactPerson>  list = customerPoolService.customerContactPersonList(pageIndex,pageSize,sortName,sortOrder,customer_id,isSeniorExecutive,abolishState);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),list);
        }catch(Exception e){
            log.error("customer customerContactPersonList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 根据客户id查询联系人列表
     * @param customerId 客户id
     * @return
     */
    @GetMapping("/selectContactPersonListByCustomerId")
    public DataResponse selectContactPersonListByCustomerId(@RequestParam(value="customerId") String customerId){
        try{
            List<CustomerContactPerson>  list = customerPoolService.selectContactPersonListByCustomerId(customerId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),list);
        }catch(Exception e){
            log.error("customer selectContactPersonListByCustomerId error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 客户详情-新增联系人  客户下联系人和联系人大表同时新增
     * @param customerContactVO 联系人实体
     * @return
     */
    @PostMapping("/addCustomerContactPerson")
    public DataResponse addCustomerContactPerson(@RequestBody CustomerContactVO customerContactVO) {
        Boolean result = customerPoolService.addCustomerContactPerson(customerContactVO);
        if (result) {
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        } else {
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 根据联系人id,回显联系人信息
     * @param customerContactPersonId 客户下联系人id
     * @return
     */
    @PostMapping("/getCustomerContactPerson")
    public DataResponse getCustomerContactPerson(@RequestParam(value="customerContactPersonId",required = false) String customerContactPersonId){
        try{
            CustomerContactPerson customerContactPerson = customerPoolService.getCustomerContactPerson(customerContactPersonId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerContactPerson);
        }catch(Exception e){
            log.error("customer getCustomerContactPerson error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 客户详情-修改联系人  同时修改客户下联系人和联系人大表
     * @param customerContactVO 联系人类
     * @return
     */
    @PostMapping("/updateCustomerContactPerson")
    public DataResponse updateCustomerContactPerson(@RequestBody CustomerContactVO customerContactVO) {
        Boolean result = customerPoolService.updateCustomerContactPerson(customerContactVO);
        if (result) {
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        } else {
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }


    /**
     * 根据客户id查询公司修改记录
     * @param pageIndex 页码
     * @param pageSize 分页大小
     * @param sortName 排序列名字
     * @param sortOrder 排序规则(asc/desc)
     * @param customerId 客户id
     * @return
     */
    @PostMapping("/modificationRecordList")
    public DataResponse modificationRecordList(
            @RequestParam(value = "pageIndex", required = true) Integer pageIndex,
            @RequestParam(value = "pageSize", required = true) Integer pageSize,
            @RequestParam(value="sortName",required = false) String sortName,
            @RequestParam(value="sortOrder",required = false) String sortOrder,//排序(asc/desc)
            @RequestParam(value="customerId") String customerId){
        try{
            DhPageInfo<ModificationRecordVO>  list = customerPoolService.modificationRecordList(pageIndex,pageSize,sortName,sortOrder,customerId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),list);
        }catch(Exception e){
            log.error("customer modificationRecordList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 修改客户池
     * @param customerPoolAddQO
     * @return
     */
    @PostMapping("/editCustomerPool")
    public DataResponse editCustomerPool(HttpServletRequest request,
                                        @RequestBody CustomerPoolAddQO customerPoolAddQO) {
        try {
            int result = customerPoolService.editCustomerPoolById(customerPoolAddQO);
            if (result == 0) {
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            } else if (result == 1){
                return new DhResponse(ResponseCodeEnum.CUSTOMER_POOL_NAME_EXIST.getResponseCode());
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }catch(Exception e){
            log.error("customer editCustomerPool error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     *客户详情--联系人 开启/废止联系人
     * @param fzCustomerContact 废止联系人实体
     * @return
     */
    @PostMapping("/updateAbolishState")
    public DataResponse updateAbolishState(FzCustomerContactVO fzCustomerContact) {
        try{
            Boolean result =  customerPoolService.updateAbolishStateById(fzCustomerContact);
            if(result){
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }catch(Exception e){
            log.error("customer updateAbolishState error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 客户-修改客户
     * @param customer 客户实体
     * @return
     */
    @PostMapping("/updateCustomer")
    public DataResponse updateCustomer(@RequestBody Customer customer) {
        Boolean result = customerPoolService.updateCustomer(customer);
        if (result) {
            Customer es = customerService.selectCustomerById(customer.getCustomerId());
            syncES(es,es.getAccountId(),"客户详情-客户编辑");
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        } else {
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 客户-修改客户图片和标签
     * @param customer 客户实体
     * @return
     */
    @PostMapping("/updateCustomerImgAndTag")
    public DataResponse updateCustomerImgAndTag(@RequestBody Customer customer) {
        Boolean result = customerPoolService.updateCustomerImgAndTag(customer);
        if (result) {
            Customer es = customerService.selectCustomerById(customer.getCustomerId());
            syncES(es,es.getAccountId(),"客户详情-客户标签");
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        } else {
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 查询客户池公司
     */
    @GetMapping("/selectCustomerPoolCompany")
    public DataResponse selectCustomerPoolCompany(@RequestParam(value="customerPoolId",required = false)String customerPoolId){
        try {
            List<JSONObject> companyList = customerPoolCompanyService.selectCustomerPoolCompany(customerPoolId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), companyList);
        } catch (Exception e) {
            log.error("customer selectCustomerPoolCompany error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 查询客户池规则
     */
    @GetMapping("/selectCustomerPoolRule")
    public DataResponse selectCustomerPoolRule(@RequestParam(value="customerPoolId",required = true)String customerPoolId){
        try {
            JSONObject customerPoolRule = customerPoolRuleService.selectCustomerPoolRule(customerPoolId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), customerPoolRule);
        } catch (Exception e) {
            log.error("customer selectCustomerPoolRule error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 删除客户池
     */
    @PostMapping("/deleteCustomerPool")
    public DataResponse deleteCustomerPool(@RequestParam(value="customerPoolId",required = true)String customerPoolId){
        try {
            customerPoolService.deleteCustomerPoolById(customerPoolId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        } catch (Exception e) {
            log.error("customer deleteCustomerPool error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 回显客户详情
     * @param customerId 客户id
     * @return
     */
    @PostMapping("/selectByCustomerId")
    public DataResponse selectByCustomerId(@RequestParam(value="customerId",required = false) String customerId){
        try{
            CustomerVO customer = customerPoolService.selectByCustomerId(customerId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customer);
        }catch(Exception e){
            log.error("customer selectByCustomerId error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 根据客户id查询需求分析
     * @param pageIndex 页码
     * @param pageSize 分页大小
     * @param sortName 排序列名字
     * @param sortOrder 排序规则(asc/desc)
     * @param customerId 客户id
     * @return
     */
    @PostMapping("/demandAnalysisList")
    public DataResponse demandAnalysisList(
            @RequestParam(value = "pageIndex", required = true) Integer pageIndex,
            @RequestParam(value = "pageSize", required = true) Integer pageSize,
            @RequestParam(value="sortName",required = false) String sortName,
            @RequestParam(value="sortOrder",required = false) String sortOrder,//排序(asc/desc)
            @RequestParam(value="customerId") String customerId){
        try{
            DhPageInfo<DemandAnalysis>  list = customerService.demandAnalysisList(pageIndex,pageSize,sortName,sortOrder,customerId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),list);
        }catch(Exception e){
            log.error("customer demandAnalysisList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 客户详情-新增需求分析
     * @param demandAnalysis 需求分析实体
     * @return
     */
    @PostMapping("/addDemandAnalysis")
    public DataResponse addDemandAnalysis(@RequestBody DemandAnalysis demandAnalysis) {
        Boolean result = customerService.addDemandAnalysis(demandAnalysis);
        if (result) {
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        } else {
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 根据客户池ID查询公司(分公司公有池)
     * @param customerPoolId  ---客户池ID
     * @return
     */
    @GetMapping("/selectBranchCompany")
    public DataResponse selectBranchCompany(@RequestParam(value="customerPoolId",required = true) String customerPoolId){
        try{
            List<UserCompanyVO> userCompanyVOList = customerPoolService.selectDistributeCompany(customerPoolId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),userCompanyVOList);
        }catch(Exception e){
            log.error("CustomerPoolController selectBranchCompany error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 根据线用户名查询用户信息及公司信息(全国的)
     * @param userName  ---用户名
     * @return
     */
    @GetMapping("/selectUserAndCompanyByName")
    public DataResponse selectUserAndCompanyByName(@RequestParam(value="userName",required = true) String userName){
        try{
            List<UserCompanyVO> userCompanyVO = customerPoolService.selectUserAndCompany(userName);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),userCompanyVO);
        }catch(Exception e){
            log.error("CustomerPoolController selectUserAndCompanyByName error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 根据客户池ID、用户名查询用户信息及公司信息(全国的)
     * @param customerPoolId  ---客户池ID
     * @param userName        ---用户名
     * @return
     */
    @GetMapping("/selectUserByPoolPermission")
    public DataResponse selectUserByPoolPermission(@RequestParam(value="customerPoolId",required = true) String customerPoolId,
                                                   @RequestParam(value="userName",required = false) String userName
    ){
        try{
            List<UserCompanyVO> userCompanyVOList = customerPoolService.selectDistributeCompany(customerPoolId);
            if(userCompanyVOList != null && userCompanyVOList.size() > 0){
                List<String> companyIds = userCompanyVOList.stream().map(company -> company.getCompanyId()).collect(Collectors.toList());
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerPoolService.selectUserByPoolPermission(companyIds,userName));
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }catch(Exception e){
            log.error("CustomerPoolController selectUserByPoolPermission error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 查询启用的客户池名称
     * @param request
     * @return
     */
    @GetMapping("/selectEnableCustomerPoolName")
    public DataResponse selectEnableCustomerPoolName(HttpServletRequest request){
        try {
            List<CustomerPool> customerPool = customerPoolService.selectEnableCustomerPoolName();
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerPool);
        } catch (Exception e) {
            log.error("CustomerPoolController selectEnableCustomerPoolName error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    private void syncES(Customer customer,String accountId,String msg) {

        String token = getToken(accountId,msg);

        Map<String, Object> parMap = transBean2Map(customer);
        parMap.put("authorization",token);
        parMap.put("key",accountId);
        try {
            String result = HttpUtil.post(ESurl+"/cutomer/insertOrUpdate",parMap);
            log.info(result);
        } catch (HttpException e) {
            log.info(msg+"ES同步失败");
        }
    }

    private String getToken(String accountId, String msg) {
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("accountId", accountId);
        try {
            return HttpUtil.post(ESurl+"/token/initToken",tokenMap);
        } catch (Exception e) {
            log.info(msg+"获取token失败");
        }
        return null;
    }


    /**
     * 对象装换map
     * @param obj
     * @return
     */
    private static Map<String, Object> transBean2Map(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 得到property对应的getter方法
                Method getter = property.getReadMethod();
                Object value = getter.invoke(obj);
                map.put(key, value);

            }
        } catch (Exception e) {
            System.out.println("transBean2Map Error " + e);
        }
        return map;
    }
}
